<template>
  <div style="border: 1px solid #ccc;">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="html"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
        @onChange="onChange"
    />
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
//编辑器配置
export default {
  data() {
    return {
      editor: null,
      html: '',
      toolbarConfig: { },
      editorConfig: { placeholder: '来和大家分享吧...',MENU_CONF: {} },
      mode: 'default', // or 'simple'
      allImg:[],
      nowImg:[],
      editImg:[],
      progress:null,
    }
  },
  components: { Editor, Toolbar },
  methods: {
    getNewTime(){
      return Math.round(new Date().getTime() / 1000)
    },
    onCreated(editor) { //编辑器创建完成
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      if(this.zt){
        //修改文章 将父组件的内容传入 并且获取已经存在的所有图片
        this.editor.setHtml(this.perception_body)
        this.allImg = this.editor.getElemsByType('image')?.map(v=>v?.src)
      }
      // this.allImg = this.editor.getElemsByType('image')?.map(v=>v?.src) //收集原文字内的图片信息
      // console.log(this.editor.getAllMenuKeys())
      // console.log(this.editor.getMenuConfig('uploadImage'))

    },
    onChange(editor){ //编辑器发送改变
      this.$emit("get_html",editor.getHtml(),this.editor,this.allImg,this.editImg)
    },
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  created() {
    let _this = this
    this.editorConfig.MENU_CONF['uploadImage'] = {
      // 上传图片的配置
      maxFileSize: 5*1024*1024,
      maxNumberOfFiles: 20,
      fieldName: 'perception',
      server: 'http://api.pinggai8.com/article/imgAdd',
      headers: {
        timestamp: _this.getNewTime(),
        userAuth: localStorage.getItem("userToken")
      },
      onBeforeUpload(file) {
        // file 选中的文件，格式如 { key: file }
        _this.editorConfig.MENU_CONF['uploadImage'].headers.timestamp = _this.getNewTime()
        if(_this.editor.getElemsByType('image').length>=20){
          _this.$notify.error({
            title: '出错啦/(ㄒoㄒ)/~~',
            message: "你当前一篇文章只能上传20张图片哦",
          })
          return false
        }else{
          return file
        }
        // 可以 return
        // 1. return file 或者 new 一个 file ，接下来将上传
        // 2. return false ，不上传这个 file
      },
      onProgress(progress) {
        if(_this.progress!=null){
          if(_this.progress.type=='success'){
            _this.progress.close()
            _this.progress = null
            return;
          }
          // _this.progress.close()
          _this.progress.message = `上传进度：${progress}%`
          return
        }
        _this.progress = _this.$notify({
          title: '上传图片中',
          message: `上传进度：${progress}%`,
          duration: 0,
          showClose: false
        });
      },
      onSuccess(file, res) { //图片上传成功 并且插入编辑器了
        if(_this.progress==null){ //如果已经完成 但是插入时又出现100 直接忽视
          return;
        }else{
          _this.progress.message = `图片上传成功`
          _this.progress.title = '成功啦(*^_^*)'
          _this.progress.type = 'success'
          setTimeout(()=>{
            if(_this.progress!=null){
              _this.progress.close()
              _this.progress = null
            }
          },2000)
        }
      },
      onFailed(file, res) { //上传失败
        _this.$notify({
          title: '出错啦/(ㄒoㄒ)/~~',
          message: "上传失败,请联系管理员"+res,
          type: 'error'
        })
      },
      onError(file, err, res) { //上传出错 可能存在超时
        console.log(`${file.name} 上传出错`, err.toString())
        if(err.toString().indexOf('maximum allowed size')!=-1){
          _this.$notify({
            title: '出错啦/(ㄒoㄒ)/~~',
            message: "图片大小不能超过5M哦",
            type: 'error'
          })
        }else{
          _this.$notify({
            title: '出错啦/(ㄒoㄒ)/~~',
            message: '请截图给管理员'+err.toString(),
            type: 'error'
          })
        }
      },
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        if(res.status==200){
          insertFn(res.data[0].replace(/public/, 'http://cloud.pinggai8.com'))
        }else{
          if(_this.progress!=null){
            _this.progress.close()
            _this.progress = null
          }
          _this.$notify({
            title: '出错啦/(ㄒoㄒ)/~~',
            message: res.msg,
            type: 'error'
          })
        }
      },
    }
    //插入图片时 将图片压入allImg
    this.editorConfig.MENU_CONF['insertImage'] = {
      onInsertedImage(imageNode) {
        if (imageNode == null) return
        if(_this.zt){
          _this.editImg.push(imageNode.src)
          localStorage.setItem('editaddtupian',_this.editImg)
          return;
        }
        _this.allImg.push(imageNode.src)
        localStorage.setItem('fabutupian',_this.allImg)
      },
    }
  },
  props:{
    perception_body:{type:String,default:""},
    zt:{type:Boolean,default: false},//默认状态为false表示添加文章，true为修改文章
  },
}
</script>

<style>
/*.w-e-toolbar{
  z-index:2 !important;
}
.w-e-text-container{
  z-index:1 !important;
}*/

</style>
